package com.holystone.orca.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.holystone.orca.common.JSONMapper;
import com.holystone.orca.common.PageData;
import com.holystone.orca.sys.aop.SystemControllerLog;
import com.holystone.orca.sys.common.SystemConstant;
import com.holystone.orca.sys.model.StaffVO;
import com.holystone.orca.sys.mybatis.model.SysCompany;
import com.holystone.orca.sys.mybatis.model.SysDepartment;
import com.holystone.orca.sys.mybatis.model.SysPerson;
import com.holystone.orca.sys.mybatis.model.SysPrivilege;
import com.holystone.orca.sys.mybatis.model.SysRole;
import com.holystone.orca.sys.service.IStaffRoleService;
import com.holystone.orca.sys.service.ISysCompanyService;
import com.holystone.orca.sys.service.ISysDepartmentService;
import com.holystone.orca.sys.service.ISysOperationLogService;
import com.holystone.orca.sys.service.ISysPersonService;
import com.holystone.orca.sys.service.ISysRoleService;
import com.holystone.orca.sys.service.ISysStaffService;
import com.holystone.orca.util.code.Md5Util;

@Controller
@RequestMapping("/sys/person_management")
public class SysPersonController {

	private static Logger logger = Logger.getLogger(SysPersonController.class);

	private static String LOGIN_KEY = "loginKey";

	private SystemConstant systemConstant;

	private String baseUrl = "sys/person_management/";

	@Resource(name="sysDepartmentService")
	private ISysDepartmentService sysDepartmentService;

	@Resource(name="RoleService")
	private ISysRoleService roleService;

	@Resource(name="StaffService")
	private ISysStaffService staffService;

	@Resource(name="StaffRoleService")
	private IStaffRoleService staffRoleService;

	@Resource(name="sysPersonService")
	private ISysPersonService sysPersonService;

	@Resource(name="sysOperationLogService")
	private ISysOperationLogService sysOperationLogService;

	@Resource(name="sysCompanyService")
	private ISysCompanyService sysCompanyService;

	@RequestMapping("/menuPersonList")
	public ModelAndView initPersonList(){
		ModelAndView model = new ModelAndView(baseUrl+"depPerson_management");
		return model;
	}

	//分页，初始化用户页面
	@ResponseBody
	@RequestMapping("/pagingPersonList")
	public ModelMap pagingPersonList(String  iPageNo, String iPageSize,String personName,String depId){
		int pageindex = iPageNo != null ? Integer.parseInt(iPageNo)
				: SystemConstant.default_pageNum;
		int pagesize = iPageSize != null ? Integer.parseInt(iPageSize)
				: SystemConstant.default_pageSize;
		PageData pageData = new PageData();
		try {
			pageData = sysPersonService.pagingSysPerson(pageindex, pagesize,
					depId, personName);
		} catch (Exception e) {
			logger.error(e, e);
		}
		return JSONMapper.createReturnMap(null, pageData, null);
	}

	//添加修改页面
	@RequestMapping(value="/initEditSysPerson")
	public ModelAndView initEditSysPerson(String personId,String opera){
		logger.debug(">>>initEditSysPerson(String personId,String opera)初始化用户添加修改页面");
		ModelAndView view = new ModelAndView(baseUrl+"add_person");
		List<SysDepartment> sysDeptarment=null;
		List<SysRole> sysRole=null;
		List<SysCompany> sysCmp=null;
		if(opera!=null&&opera.equals("add")){//添加
			try {
				sysDeptarment=sysDepartmentService.selectDeptName();
				sysRole=roleService.getRoleList();
				sysCmp=sysCompanyService.selectCompany();
			} catch (Exception e) {
				logger.error(e,e);
			}
			view.addObject("sysDeptarment", sysDeptarment);
			view.addObject("sysRole", sysRole);
			view.addObject("sysCmpList", sysCmp);
		}else if(opera!=null&&opera.equals("edit")){//修改
			StaffVO sysPerson=null;
			try {
				sysDeptarment=sysDepartmentService.selectDeptName();
				sysCmp=sysCompanyService.selectCompany();
				Map<Object,String> staffMap = new HashMap<Object,String>();
				staffMap.put("personId", personId);
				sysPerson = sysPersonService.selectStaffVOByPersonCode(staffMap);
				int depId=staffService.selectDepIdByPersonId(Integer.parseInt(personId));
				view.addObject("depId", depId);
			} catch (Exception e) {
				logger.error(e,e);
			}
			sysRole=roleService.getRoleList();
			Map<String,String> map=new HashMap<String,String>();
			map.put("personId", personId);
			int roleId=roleService.getStaffRoleByPersonId(map);
			view.addObject("sysStaffVO", sysPerson);
			view.addObject("sysDeptarment", sysDeptarment);
			view.addObject("sysRole", sysRole);
			view.addObject("roleId", roleId);
			view.addObject("sysCmpList", sysCmp);
		}
		logger.debug("<<<initEditSysPerson(StaffVO staffVO)");
		return view;
	}


	//点击添加按钮
	@ResponseBody
	@RequestMapping("/insertSysPerson")
	@SystemControllerLog(description = "添加用户")
	public ModelMap insertSysPerson(SysPerson sysPerson,String depId,String roleName,String personPassword,ModelMap modelMap){
		boolean flag=false;
		//MD5加密密码
		String pwd=Md5Util.EncoderByMd5(personPassword);
		sysPerson.setPersonPassword(pwd);
		Map<Object,String> map = new HashMap<Object,String>();
		map.put("depId", depId);
		SysPerson viSysPerson=null;
		String msg = "添加失败!";
		try {
			viSysPerson = sysPersonService.selectPersonByPersonCode(sysPerson.getPersonCode());
			if(viSysPerson == null){
				flag=(sysPersonService.insertPerson(sysPerson));//插入sys_person表信息
				map.put("personId", sysPerson.getPersonId()+"");
				flag=(flag&&staffService.insertStaffByPersonId(map)&&//插入sys_staff表信息
						staffRoleService.insertStaffRole(roleName));//插入sys_staff_role表中信息
				msg = "添加成功！";
			}else{
				msg = "添加失败!登录名重复！";
			}
		} catch (Exception e) {
			logger.error(e,e);
		}
		modelMap = JSONMapper.createReturnMap(null, null, flag);
		modelMap.put("msg", msg);
		return modelMap;
	}

	//修改用户信息
	@ResponseBody
	@RequestMapping("/updateSysPerson")
	public ModelMap updateSysPerson(SysPerson sysPerson,String personId,String roleName,String depId,ModelMap modelMap){
		boolean flag=false;
		Map<Object,String> map=new HashMap<Object,String>();
		map.put("personId", personId);
		map.put("roleName", roleName);
		Map<Object,String> staffRolemap=new HashMap<Object,String>();
		staffRolemap.put("personId", personId);
		staffRolemap.put("depId", depId);
		Map<Object,String> map1 = new HashMap<Object,String>();
		map1.put("personId", sysPerson.getPersonId()+"");
		map1.put("personCode", sysPerson.getPersonCode());
		SysPerson viSysPerson=null;
		StaffVO staffVO = null;
		String msg = "修改失败!";
		try {

			viSysPerson = sysPersonService.selectPersonByPersonCode(sysPerson.getPersonCode());
			staffVO = sysPersonService.selectStaffVOByPersonCode(map1);
			if(viSysPerson == null || staffVO != null){
				//修改三个表中的数据
				flag=(sysPersonService.updatePerson(sysPerson)&&
						staffService.updateStaffByPersonId(staffRolemap)&&
						staffRoleService.updateStaffRoleByPersonId(map));
			}else{
				msg = "修改失败！登录名重复！";
			}
		} catch (Exception e) {
			logger.error(e,e);
		}
		modelMap = JSONMapper.createReturnMap(null, null, flag);
		modelMap.put("msg", msg);
		return modelMap;
	}


	//删除点击的用户
	@ResponseBody
	@RequestMapping("/deletePerson")
	public ModelMap deletePerson(int personId){
		boolean flag=false;
		try {
			flag=(sysPersonService.deletePersonByPersonId(personId)&&
					staffRoleService.deleteStaffRoleByPersonId(personId)&&
					staffService.deleteStaffByPersonId(personId)
			);
		} catch (Exception e) {
			logger.error(e,e);
		}
		return JSONMapper.createReturnMap(null, null, flag);
	}

	//多项删除，删除选定的用户
	@ResponseBody
	@RequestMapping("/deleteSelectSysPerson")
	@RequiresRoles("admin")
	public ModelMap deleteSelectSysPerson(String checkedDel){
		boolean flag=false;
		checkedDel=checkedDel.substring(0, checkedDel.length() - 1);
		String[] arry=null;
		arry=checkedDel.split(",");
		List<Integer> list=new ArrayList<Integer>();
		for(int i=0;i<arry.length;i++){
			list.add(Integer.parseInt(arry[i]));
		}
		try {
			flag=(
					//分别删除三个表中的数据，删除顺序不可改变
					sysPersonService.delSelectPerson(list)&&
							staffRoleService.delSelectStaffRole(list)&&
							staffService.delSelectStaff(list)
			);
		} catch (Exception e) {
			logger.error(e,e);
		}
		return JSONMapper.createReturnMap(null, null, flag);
	}
	@RequestMapping("/menuEditPassword")
	public ModelAndView menuEditPassword(ModelMap modelMap){
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		HttpSession contextSess = attr.getRequest().getSession(true);
		StaffVO staffVO = (StaffVO)contextSess.getAttribute(SystemConstant.SESSION_STAFF_KEY);
		ModelAndView model = new ModelAndView(baseUrl+"edit_password");
		modelMap.put("personId", staffVO.getPersonId());
		return model;
	}

	@ResponseBody
	@RequestMapping("editPassword")
	public ModelMap editPassword(String password,String newPassword,String personId){
		//MD5加密密码
		String pwd=Md5Util.EncoderByMd5(password);
		boolean flag = false;
		Map<Object,String> map = new HashMap<Object,String>();
		map.put("newPassword", Md5Util.EncoderByMd5(newPassword));
		map.put("personId", personId);
		if(!pwd.equals(sysPersonService.selectByPersonId(personId).getPersonPassword())){
			return JSONMapper.createReturnMap("密码错误！", null, false);
		}else{
			try {
				flag = sysPersonService.editPassword(map);
			} catch (Exception e) {
				logger.error(e,e);
			}
			return JSONMapper.createReturnMap(null, null, flag);
		}
	}


	//初始化ztree，查询出权限信息，拼接字符串，前端生成树
	@ResponseBody
	@RequestMapping("/initDepPersonTree")
	public ModelMap initDepPersonTree(){
		ModelMap modelMap = new ModelMap();
		List<SysDepartment> sysDepartmentList=sysDepartmentService.selectAllList();
		String nodes = "";
		for(int i=0;i<sysDepartmentList.size();i++){
			nodes +="{id:"+sysDepartmentList.get(i).getDepId()+", pId:"
					+sysDepartmentList.get(i).getDepPid()+", name:\""+sysDepartmentList.get(i).getDepName()
					+"\" , open:true},";
			//lstTree.add(nodes);
		}
		if(nodes != ""){
			nodes = nodes.substring(0, nodes.length() - 1);
		}
		nodes ="["+nodes+"]";
		modelMap.put("lstTree", nodes);
		return modelMap;
	}
}